package com.example.myapplication06;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {
    private EditText accountEdit;
    private EditText passwordEdit;

    private MySQLiteOpenHelper helper;
    private SQLiteDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);

        helper = new MySQLiteOpenHelper(LoginActivity.this,"androidCourse",null,1);
        database = helper.getWritableDatabase();

        accountEdit = findViewById(R.id.login_account);
        passwordEdit = findViewById(R.id.login_password);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        database.close();
    }

    public void login(View view) {
        String accountInput = accountEdit.getText().toString();
        String passwordInput = passwordEdit.getText().toString();

        Cursor cursor = database.query("user",null,"account=?",new String[]{accountInput},null,null,null);
        if(cursor.getCount() == 0){
            Toast.makeText(this, "账号未注册！！", Toast.LENGTH_SHORT).show();
        }else {
            cursor.moveToNext();
            String password = cursor.getString(cursor.getColumnIndex("password"));
            if(password.equals(passwordInput)){
                Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show();
            }else {
                passwordEdit.setText("");
                Toast.makeText(this, "密码错误，请重新输入！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void goAdd(View view) {
        Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
        startActivity(intent);
    }
}